import {db} from "@/lib/db";
import memoize from "memoize";

export const memorizedIgnoredWords = memoize(async () => await getIgnoredWords(), {maxAge: 5000});

async function getIgnoredWords() {
    const results = await db.word_ignored.findMany();
    return results.map(w => w.word)
}

export async function getRankHist(histDays: number = 30): Promise<string[]> {
    const dt = new Date();
    const ignoredWords = await db.word_ignored.findMany();
    const ignored = ignoredWords.map(w => w.word.toUpperCase());
    const result = await db.tb_rank_hist.findMany({
        where: {
            rank_date: {
                lt: dt
            }
        },
        orderBy: {
            rank_date: 'desc'
        },
        take: histDays
    })
    const platesArr = result.map(r => [r.no_1, r.no_2, r.no_3, r.no_4, r.no_5, r.df_1, r.df_2, r.df_3, r.df_4, r.df_5, r.th_1, r.th_2, r.th_3, r.th_4, r.th_5])
    const plates = platesArr.flat()
    const uniquePlates = plates.filter((v, index, selfArr) => index === selfArr.findIndex(s => s === v))
    // console.log(uniquePlates)
    const filtered: string[] = uniquePlates.filter((item): item is string => item !== null && item !== '')
    return filtered.filter(p => !ignored.includes(p.toUpperCase()))
}